package ua.lk.phonebook;

import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;

import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class CheckLogonFilter
 */
@WebFilter(
		dispatcherTypes = {
				DispatcherType.REQUEST, 
				DispatcherType.FORWARD, 
				DispatcherType.INCLUDE, 
				DispatcherType.ERROR
		},

		description = "Фильтр, проверяющий наличие активно сессии", 
		urlPatterns = { 
				//"/CheckLogonFilter", 
				"/*"
		}, 
		initParams = { 
				@WebInitParam(name = "avoid-urls", value = "/index.jsp,/login.jsp,/checklogin,/css/styles.css,/img/109ico4.ico", description = "Список исключений фильтра")
		})
public class CheckLogonFilter implements Filter {

	private final String LOGIN_PAGE = "login.jsp";
	private ArrayList<String> urlList;
    /**
     * Default constructor. 
     */
    public CheckLogonFilter() {
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;
		//String url = req.getServletPath().substring(1); // убрать начальный слэш
		String url = req.getServletPath();
		String query = req.getQueryString();
		/*	
		System.out.println(url);
	
		System.out.println("");
		System.out.println("getRequestURL = "+req.getServletPath());
		System.out.println("getPathInfo = "+req.getPathInfo());
		System.out.println("getQueryString = "+req.getQueryString());
*/		
		boolean allowedRequest = false; 
		if( urlList.contains(url)) {
			allowedRequest = true;
		}
		if(!allowedRequest)
		{
//			HttpSession session = req.getSession(false);
// не работает, т.к. нельзя выполнить редирект при отсутствии сессии.
			HttpSession session = req.getSession();
			//System.out.println(session);
			if( session.getAttribute("login") == null)
			{
				if(query != null)
					url += "?"+query.replace("&", "$");
				resp.sendRedirect(LOGIN_PAGE+"?backto="+url);
			//	req.getRequestDispatcher(LOGIN_PAGE+"?backto="+url).forward(req, resp);
			}
		}
			
		//System.out.println(allowedRequest);

		
		// pass the request along the filter chain
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
        String urls = fConfig.getInitParameter("avoid-urls");
        StringTokenizer token = new StringTokenizer(urls, ",");
 
        urlList = new ArrayList<String>();
 
        while (token.hasMoreTokens()) {
            urlList.add(token.nextToken());
        }
	}

}
